package com.hsgene.common.util.date;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间日期格式解析
 *
 * @author wangbing
 * @version 1.0, 2018/07/10
 */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static final Logger logger = LogManager.getLogger(LocalDateTimeDeserializer.class);

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {
        if (jsonParser == null || StringUtils.isEmpty(jsonParser.getText())) {
            return null;
        }
        try {
            return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        } catch (Exception e) {
            logger.error("暂不支持的日期时间格式解析：{}", jsonParser.getValueAsString());
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
